package cn.yangke.org.service.impl;

import cn.yangke.basic.service.impl.BaseServiceImpl;
import cn.yangke.org.domain.Department;
import cn.yangke.org.mapper.DepartmentMapper;
import cn.yangke.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author YangKe
 * @Date 2022/6/1 18:24
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        //新建之后调用修改方法修改dirPath地址
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        String dirPath = "";
        //判断parent是否为null
        if(department.getParent() == null){
            //如果parent为null说明新增的为顶级
            dirPath = "/" + department.getId();
        }else {
            //否则不为顶级,则获取到父级对象获取id,基于此id查询出父对象
            Department parent = departmentMapper.loadById(department.getParent().getId());
            //拼接dirPath
            dirPath = parent.getDirPath() + "/"+ department.getId();

        }
        //将拼接出来的dirPath设置到department对象中
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void batchRemove(Long[] ids) {
        departmentMapper.batchRemove(ids);
    }

    @Override
    public List<Department> queryTree() {
        //查询所有
        List<Department> departments = departmentMapper.loadAll();
        //创建空的map集合
        Map<Long, Department> allDepts = new HashMap<>();
        //遍历查询到的所有
        for (Department department : departments) {
            //将id作为key,对象作为value存入map集合中
            allDepts.put(department.getId(),department);
        }
        //创建一个最高的层级
        ArrayList<Department> firstDepts = new ArrayList<>();
        //再一次遍历查询全部
        for (Department tmp : departments) {
            //判断父级id是否为null
            if(tmp.getParent_id()==null){
                //如果父级id为null,那就说明已经是最高层级
                firstDepts.add(tmp);
            }else {
                //否则就通过父级id获取map集合中的父级对象
                Department parent = allDepts.get(tmp.getParent_id());
                if(parent!=null){
                    //将自己存入父级的children中
                    parent.getChildren().add(tmp);
                }
            }
        }
        
        return firstDepts;
    }
}
